package com.dyz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.dyz.domain.SysMenu;
import com.dyz.feign.JwtToken;
import com.dyz.feign.Oauth2FeignClient;
import com.dyz.model.LoginUserResult;
import com.dyz.service.ISysMenuService;
import com.dyz.service.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysLoginServiceImpl implements SysLoginService {
    @Resource
    private Oauth2FeignClient oauth2FeignClient;
    @Resource
    private ISysMenuService sysMenuService;
    @Value("${basic.token:Basic Y29pbi1jbGllbnQ6Y29pbi1zZWNyZXQ=}")
    private String basicToken;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public LoginUserResult login(String username, String password) {
        log.info("登录用户{}",username);
        //远程调用authorization-server 获取token
        ResponseEntity<JwtToken> feignClientToken = oauth2FeignClient.getToken("password", username, password, "admin_type", basicToken);
        if(feignClientToken.getStatusCode() != HttpStatus.OK){
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwtToken = feignClientToken.getBody();
        log.info("获取token{}", JSON.toJSONString(jwtToken,true));

        String token = jwtToken.getAccessToken();
        Jwt jwt = JwtHelper.decode(token);
        String claims = jwt.getClaims();
        Long userId = Long.valueOf(JSON.parseObject(claims).getString("user_name"));
        //从数据库中获取菜单信息。
        List<SysMenu> menus = sysMenuService.selectMenuByUserId(userId);
        JSONArray jsonArray = JSON.parseObject(claims).getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorities = null;
        //获取权限信息
        if(jsonArray != null){
            authorities = jsonArray.stream().map((per)->new SimpleGrantedAuthority(per.toString())).collect(Collectors.toList());
        }
        stringRedisTemplate.opsForValue().set(token,"",  jwtToken.getExpiresIn(),TimeUnit.SECONDS);
        return new LoginUserResult(jwtToken.getTokenType()+" "+token, menus, authorities);
    }
}
